package com.argesone.third.shanxiyingji.loginadapter.utils;

import cn.hutool.core.util.HexUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 * HmacSHA1 加密工具包
 * </p>
 *
 * @author GuiChen
 */
@Slf4j
public class HmacSHA1Util {

    /**
     * HmacSHA1 加密方式
     */
    public static final String HMAC_SHA_1 = "HmacSHA1";

    /**
     * HmacSHA1 加密算法
     *
     * @param src 待加密的字符串（已转大写）
     * @param key secretKey
     * @return {@link String}
     */
    public static String encode(String src, String key) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HMAC_SHA_1);
            Mac mac = Mac.getInstance(HMAC_SHA_1);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(src.getBytes(StandardCharsets.UTF_8));
            return HexUtil.encodeHexStr(rawHmac);
        } catch (Exception e) {
            log.error("--->>> HmacSHA1Util encode error.", e);
        }
        return null;
    }

}
